package com.heimachefu.config;

import com.heimachefu.module.resource.entity.ResourceEntity;
import com.heimachefu.module.user.dao.UserRepository;
import com.heimachefu.module.user.entity.UserEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author liuxingdong@heimachefu.com
 * @date 2019/7/19 11:37
 */
@Component
public class VersionSystemSuccessHandler implements AuthenticationSuccessHandler {
    @Value("${server.servlet.context-path}")
    private String BASE_URL;
    private Logger logger = LoggerFactory.getLogger(getClass());
    private final UserRepository userRepository;

    @Autowired
    public VersionSystemSuccessHandler(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        System.out.println("当前登录成功 = ");
        UserEntity userEntity = (UserEntity)authentication.getPrincipal();
        List<ResourceEntity> resourceEntityList = userRepository.getAuthResourceForUser(userEntity.getUserId());
        if(resourceEntityList != null && !resourceEntityList.isEmpty()){
            httpServletRequest.getSession().setAttribute("resourceList",resourceEntityList);
        }
        String menuId = httpServletRequest.getParameter("menuId");
        System.out.println("menuId = " + menuId);
        if(StringUtils.hasText(menuId)){
            httpServletRequest.getSession().setAttribute("menuId",menuId);
        }
        httpServletResponse.sendRedirect(BASE_URL+"/home/main");
    }
}
